package server.business.service.Impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import server.business.pojo.*;
import server.business.mapper.BloodOrderMapper;
import server.business.mapper.OrderBloodReviewMapper;
import server.business.mapper.OrderBloodStateMapper;
import server.business.service.BloodOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import server.business.service.OrderBloodReviewService;
import server.business.utils.UUIDUtils;
import server.business.vo.Result;
import server.business.vo.ResultExpand;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service("orderBloodService")
public class BloodOrderServiceImpl extends ServiceImpl<BloodOrderMapper, BloodOrderData> implements BloodOrderService {
    @Autowired
    private BloodOrderService bloodOrderService;
    @Autowired
    private BloodOrderMapper bloodOrderMapper;
    @Autowired
    private OrderBloodStateMapper orderBloodStateMapper;
    @Autowired
    private OrderBloodReviewMapper orderBloodReviewMapper;
    @Autowired
    private OrderBloodReviewService orderBloodReviewService;
    
    public IPage<BloodOrderData> selectByPage(int currentPage, int pageSize){
        Page<BloodOrderData> page = new Page<>(currentPage, pageSize);
        IPage<BloodOrderData> orderBloodDataIPage = bloodOrderMapper.selectPage(page, null);
        return orderBloodDataIPage;
    }

    /**
     * 查询数据
     *
     * @return {@link List}<{@link BloodOrderData}>
     */
    public List<BloodOrderData> queryData(){
        List<BloodOrderData> bloodOrderData = bloodOrderService.list();
        return bloodOrderData;
    }

    /**
     * 分页查询
     *
     * @param request  请求
     * @param response 响应
     * @return {@link ResultExpand}
     */
    public ResultExpand listByPage(HttpServletRequest request, HttpServletResponse response){
        Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));
        IPage<BloodOrderData> orderBloodIPage = bloodOrderService.selectByPage(currentPage, pageSize);
        ResultExpand resultExpand = new ResultExpand("200", "成功", orderBloodIPage.getRecords(), currentPage, pageSize, orderBloodIPage.getTotal(), orderBloodIPage.getPages());
        response.setStatus(200);
        return resultExpand;
    }
    

    /**
     * 搜索血秩序
     *
     * @param request  请求
     * @param response 响应
     * @return {@link ResultExpand}
     */
    public ResultExpand searchBloodOrder(HttpServletRequest request, HttpServletResponse response){
        //接收参数
        String number = request.getParameter("number");
        String bloodType = request.getParameter("bloodType");
        String state = request.getParameter("state");
        String aboBloodType = request.getParameter("aboBloodType");
        String rhBloodType = request.getParameter("rhBloodType");
        String applicant = request.getParameter("applicant");
        String applicantNumber = request.getParameter("applicantNumber");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));
        //创建分页对象
//        IPage<BloodOrderData> page = new Page<>(currentPage, pageSize);
        //创建查询条件
        QueryWrapper<BloodOrderData> queryWrapper = new QueryWrapper<>();
        //订单未删除
        queryWrapper.eq("is_deleted", 0);
        if(number != "")
            queryWrapper.eq("number", number);
        if(bloodType != "")
            queryWrapper.eq("blood_type", bloodType);
        if(aboBloodType != "")
            queryWrapper.eq("abo_blood_type", aboBloodType);
        if(rhBloodType != "")
            queryWrapper.eq("rh_blood_type", rhBloodType);
        if(state != "")
            queryWrapper.eq("t1.state", state);
        if(applicant != "")
            queryWrapper.like("applicant", applicant);
        if(applicantNumber != "")
            queryWrapper.like("applicant_number", applicantNumber);
        if(startTime != "")
            queryWrapper.ge("apply_time", startTime);
        if(endTime != "")
            queryWrapper.le("apply_time", endTime + " 23:59:59");
        //查询数据库
//        bloodOrderService.page(page, queryWrapper);
        IPage<BloodOrderData> page = bloodOrderMapper.selectBloodOrderPage(
                new Page<>(currentPage, pageSize),  queryWrapper
        );
        //返回数据
        //返回的数据
        ResultExpand resultExpand = new ResultExpand();
        resultExpand.setCurrent(currentPage).setPageSize(pageSize).setTotal(page.getTotal()).setPages(page.getPages());
        resultExpand.setCode("200");
        resultExpand.setMsg("搜索成功");
        resultExpand.setData(page.getRecords());
        return resultExpand;
    }


    /**
     * 血液修改订单
     *
     * @param bloodOrderData 血订单数据
     * @return {@link Result}
     */
    public Result modifyBloodOrder(@RequestBody BloodOrderData bloodOrderData){
        //数量修改需要修改总血量和小计金额
        BigDecimal cartAmount = new BigDecimal(bloodOrderData.getCartAmount());    //份数
        BigDecimal measurementUnit = new BigDecimal(bloodOrderData.getMeasurementUnit());  //计量单位
        BigDecimal totalMoney = cartAmount.multiply(bloodOrderData.getBloodPrice());    //总价
        BigDecimal bloodVolume = cartAmount.multiply(measurementUnit);   //总血量
        bloodOrderData.setBloodVolume(bloodVolume);
        bloodOrderData.setTotalMoney(totalMoney);

        boolean success = bloodOrderService.updateById(bloodOrderData);
        Result result = new Result();
        if(success) {
            result.setCode("200");
            result.setMsg("修改成功");
        }else{
            result.setCode("500");
            result.setMsg("修改失败");
        }
        return result;
    }


    /**
     * 拒绝血秩序
     *
     * @param bloodOrderData 血订单数据
     * @return {@link Result}
     */
    public Result refuseBloodOrder(@RequestBody BloodOrderData bloodOrderData){
        //订单id
        Long orderId = bloodOrderData.getId();
        //审核人
        String auditor = bloodOrderData.getAuditor();
        //审核人工号
        String auditorNumber = bloodOrderData.getAuditorNumber();

        //"订单驳回“的code   orderState
        QueryWrapper<OrderBloodState> orderBloodStateQueryWrapper = new QueryWrapper<>();
        orderBloodStateQueryWrapper.eq("name", "订单驳回");
        OrderBloodState orderBloodState = orderBloodStateMapper.selectOne(orderBloodStateQueryWrapper);
        String orderState = orderBloodState.getCode();

        //修改订单记录，关于审核信息
        bloodOrderData.setState(orderState);
        bloodOrderData.setAuditTime(new Date());
        boolean success = bloodOrderService.updateById(bloodOrderData);

        //修改审核记录
        UpdateWrapper<OrderBloodReview> orderBloodReviewUpdateWrapper = new UpdateWrapper<>();
        orderBloodReviewUpdateWrapper.eq("number", orderId);
        orderBloodReviewUpdateWrapper.set("state", orderState);
        orderBloodReviewMapper.update(null, orderBloodReviewUpdateWrapper);

        Result result = new Result();
        if(success) {
            result.setCode("200");
            result.setMsg("审核成功");
        }else{
            result.setCode("500");
            result.setMsg("审核失败");
        }
        return result;
    }


    /**
     * 通过血液订单
     *
     * @param bloodOrderData 血订单数据
     * @return {@link Result}
     */
    public Result passBloodOrder(@RequestBody BloodOrderData bloodOrderData){
        //订单id
        Long orderId = bloodOrderData.getId();
        //审核人
        String auditor = bloodOrderData.getAuditor();
        //审核人工号
        String auditorNumber = bloodOrderData.getAuditorNumber();

        //"订单通过“的code   orderState
        QueryWrapper<OrderBloodState> orderBloodStateQueryWrapper = new QueryWrapper<>();
        orderBloodStateQueryWrapper.eq("name", "订单通过");
        OrderBloodState orderBloodState = orderBloodStateMapper.selectOne(orderBloodStateQueryWrapper);
        String orderState = orderBloodState.getCode();

        //修改订单记录，关于审核信息
        bloodOrderData.setState(orderState);
        bloodOrderData.setAuditTime(new Date());
        boolean success = bloodOrderService.updateById(bloodOrderData);

        //修改审核记录
        UpdateWrapper<OrderBloodReview> orderBloodReviewUpdateWrapper = new UpdateWrapper<>();
        orderBloodReviewUpdateWrapper.eq("number", orderId);
        orderBloodReviewUpdateWrapper.set("state", orderState);
        orderBloodReviewMapper.update(null, orderBloodReviewUpdateWrapper);

        Result result = new Result();
        if(success) {
            result.setCode("200");
            result.setMsg("审核成功");
        }else{
            result.setCode("500");
            result.setMsg("审核失败");
        }
        return result;
    }


    /**
     * 提交订单
     *
     * @param bloodOrderList  血订单列表
     * @param applicant       申请人
     * @param applicantNumber 申请人数量
     * @param applyCompany    适用于公司
     * @return {@link Result}
     */
    public Result submitOrder(@RequestBody BloodOrderData[] bloodOrderList, @RequestParam(name = "applicant") String applicant, @RequestParam(name = "applicantNumber") String applicantNumber, @RequestParam(name = "applyCompany") String applyCompany){
        //定血审核表
        List<OrderBloodReview> orderBloodReviews = new ArrayList<>();

        //"订单等待审核“的code   orderState
        QueryWrapper<OrderBloodState> orderBloodStateQueryWrapper = new QueryWrapper<>();
        orderBloodStateQueryWrapper.eq("name", "订单等待审核");
        OrderBloodState orderBloodState = orderBloodStateMapper.selectOne(orderBloodStateQueryWrapper);
        String orderState = orderBloodState.getCode();

        String number = UUIDUtils.getUUID();
        for (int i=0; i<bloodOrderList.length; i++){
            BigDecimal cartAmount = new BigDecimal(bloodOrderList[i].getCartAmount());  //数量
            BigDecimal measurementUnit = new BigDecimal(bloodOrderList[i].getMeasurementUnit());    //计量单位
            BigDecimal totalMoney =  cartAmount.multiply(bloodOrderList[i].getBloodPrice());    //单价
            BigDecimal bloodVolume = cartAmount.multiply(measurementUnit);  //血量
            //数据库相关
            bloodOrderList[i].setNumber(number);
            bloodOrderList[i].setSerialNumber(UUIDUtils.getUUID());
            //申请人相关
            bloodOrderList[i].setApplicant(applicant).setApplicantNumber(applicantNumber).setApplyCompany(applyCompany).setApplyTime(new Date());
            //订单相关
            bloodOrderList[i].setTotalMoney(totalMoney).setBloodVolume(bloodVolume).setState(orderState).setIsDeleted(0);
//            System.out.println(bloodOrderList[i].toString());
        }
        List<BloodOrderData> bloodOrderDataList = Arrays.asList(bloodOrderList);
        Boolean successOrder = bloodOrderService.saveBatch(bloodOrderDataList);

        //订单审核的List
        for (int i = 0; i < bloodOrderDataList.size(); i++) {
            BloodOrderData bloodOrderData = bloodOrderDataList.get(i);
            OrderBloodReview orderBloodReview = new OrderBloodReview();
            orderBloodReview.setNumber(bloodOrderData.getId() + "");    //订单标识
            orderBloodReview.setApplicantNumber(bloodOrderData.getApplicantNumber());   //申请人工号
            orderBloodReview.setApplyTime(bloodOrderData.getApplyTime());   //申请时间
            orderBloodReview.setState(orderState);  //状态代码
            orderBloodReviews.add(orderBloodReview);
        }

        Boolean successReview = orderBloodReviewService.saveBatch(orderBloodReviews);

        Result result = new Result();
        if(successOrder && successReview)
            result.setCode("200").setMsg("提交成功");
        else
            result.setMsg("提交失败");
        return result;
    }


    /**
     * 删除血液订单
     *
     * @param bloodOrderData 血订单数据
     * @return {@link Result}
     */
    public Result deleteBloodOrder(@RequestBody BloodOrderData bloodOrderData) {
//        System.out.println(bloodOrderData.toString());
        Long id = bloodOrderData.getId();
        int success = bloodOrderMapper.deleteById(id);
        Result result = new Result();
        if (success == 1) {
            result.setCode("200");
            result.setMsg("删除成功");
        }else{
            result.setCode("500");
            result.setMsg("删除失败");
        }
        return result;
    }


    /**
     * 下载excel
     *
     * @param request  请求
     * @param response 响应
     */
    public void downloadExcel(HttpServletRequest request, HttpServletResponse response){
        //接收参数
        String number = request.getParameter("number");
        String bloodType = request.getParameter("bloodType");
        String state = request.getParameter("state");
        String applicant = request.getParameter("applicant");
        String applicantNumber = request.getParameter("applicantNumber");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        try {
            String filename = "血液订单";
            String userAgent = request.getHeader("User-Agent");
            if(userAgent.contains("MSIE")||userAgent.contains("Trident")){
                filename = URLEncoder.encode(filename,"UTF-8");            }else {
                filename = new String(filename.getBytes("UTF-8"),"ISO-8859-1");
            }
            response.setContentType("application/json.ms-exce");
            response.setCharacterEncoding("utf-8");
            response.addHeader("Content-Disposition","filename = " + filename + ".xlsx");
            //创建查询条件
            QueryWrapper<BloodOrderData> queryWrapper = new QueryWrapper<>();
            if(number != "")
                queryWrapper.eq("number", number);
            if(bloodType != "")
                queryWrapper.eq("blood_type", bloodType);
            if(state != "")
                queryWrapper.eq("state", state);
            if(applicant != "")
                queryWrapper.like("applicant", applicant);
            if(applicantNumber != "")
                queryWrapper.like("applicant_number", applicantNumber);
            if(startTime != "")
                queryWrapper.ge("apply_time", startTime);
            if(endTime != "")
                queryWrapper.le("apply_time", endTime + " 23:59:59");
            List<BloodOrderData> bloodOrderDataList = bloodOrderService.list(queryWrapper);
            EasyExcel.write(response.getOutputStream(), BloodOrderData.class).sheet("sheet").doWrite(bloodOrderDataList);
        }catch (IOException e){
            e.printStackTrace();
        }
    }

}
